package com.capsulode.excel.domain;

import com.capsulode.excel.exception.CellFailure;
import com.capsulode.excel.exception.RowFailure;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

public class ExcelImportResult {
    private final int lines;
    private final Collection<String> ignoredColumns;
    private final Collection<RowFailure> failures;

    public ExcelImportResult(int lines, Collection<String> ignoredColumns, Collection<RowFailure> failures) {
        this.lines = lines;
        this.ignoredColumns = ignoredColumns;
        this.failures = failures;
    }

    public ExcelImportResult(int row, Collection<String> raw, int column, String header, String message) {
        lines = 0;
        ignoredColumns = Collections.EMPTY_LIST;
        failures = new ArrayList<>(1);
        RowFailure rowFailure = new RowFailure(row, raw);
        rowFailure.addFailure(new CellFailure(row, column, header, message));
        failures.add(rowFailure);
    }

    public int getLines() {
        return lines;
    }

    public Collection<String> getIgnoredColumns() {
        return ignoredColumns;
    }

    public Collection<RowFailure> getFailures() {
        return failures;
    }

    private String _stringifyCache;

    @Override
    public String toString() {
        return stringify("\n", " ");
    }

    public String toHtml() {
        return stringify("<br />", "&nbsp;");
    }

    private String stringify(CharSequence linebreaker, CharSequence blank) {
        if (_stringifyCache == null) {

            StringBuilder sb = new StringBuilder();
            if (!ignoredColumns.isEmpty()) {
                sb.append("忽略").append(ignoredColumns).append("列的数据，");
            }

            sb.append("成功导入了 ").append(lines).append(" 行");

            if (!failures.isEmpty()) {
                sb.append("，还有 ").append(failures.size()).append(" 行数据因错误被忽略：").append(linebreaker);
                failures.forEach(rf -> {
                    sb.append("第 ").append(rf.getIndex()).append(" 行").append(rf.getRaw()).append(linebreaker);
                    rf.getFailures().forEach(cf -> {
                        sb.append(blank).append(blank).append(blank).append(blank)
                                .append("第 ").append(cf.getColumn()).append(" 列【").append(cf.getHeader()).append("】")
                                .append(cf.getMessage()).append(linebreaker);
                    });
                });
            }

            _stringifyCache = sb.toString();
        }
        return _stringifyCache;
    }
}
